<template>
  <div class="adminherd-container">
    <el-container>
      <el-main>
        <div ref="chartRefUser" class="chart"></div>
        <div class="info-container">
          <div v-for="item in userData" :key="item.identity" class="user-data">
            {{ getUserTypeName(item.identity) }}: {{ item.sum }} 个用户
          </div>
        </div>

        <div ref="chartRefAuthor" class="chart"></div>
        <div class="info-container">
          <div v-for="item in AuthorBookData" :key="item.author" class="AuthorBook-data">
            {{ item.author }}: {{ item.sum }} 本
          </div>
        </div>

        <!-- 每个类型的书籍数量 阶梯线图 -->
        <div ref="charRefTypeBook" class="chart"></div>
        <div class="info-container">
          <div v-for="item in TypeBookData" :key="item.type" class="TypeBook-data">
            {{ item.type }}: {{ item.sum }} 本
          </div>
        </div>

        <!-- 每一个书籍的标签数量 阶梯线图 -->
        <div ref="chartRefBookType" class="chart"></div>
        <div class="info-container">
          <div v-for="item in BookTagData" :key="item.bookName" class="BookType-data">
              {{ item.bookName }}: {{ item.tagSum }} 个标签
          </div>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import * as echarts from 'echarts';
import axios from 'axios';
import { ElMessage } from 'element-plus';

const chartRefUser = ref(null);
const chartRefAuthor = ref(null);
const charRefTypeBook = ref(null);
const chartRefBookType = ref(null);
const userData = ref([]);
const AuthorBookData = ref([]);
const TypeBookData = ref([]);
const BookTagData = ref([]);

// 初始化图表实例
let chartInstanceUser = null;
let chartInstanceAuthor = null;
let chartInstanceTypeBook = null;
let chartInstanceBookType = null;

// 在组件卸载时移除事件监听
const resizeCharts = () => {
  chartInstanceUser && chartInstanceUser.resize();
  chartInstanceAuthor && chartInstanceAuthor.resize();
  chartInstanceTypeBook && chartInstanceTypeBook.resize();
  chartInstanceBookType && chartInstanceBookType.resize();
};

onMounted(() => {
  getUserAll();
  getAuthorBookAll();
  getTypeBookAll();
  getBookTagAll();
  window.addEventListener('resize', resizeCharts);
});

onUnmounted(() => {
  window.removeEventListener('resize', resizeCharts);
  chartInstanceUser && chartInstanceUser.dispose();
  chartInstanceAuthor && chartInstanceAuthor.dispose();
  chartInstanceTypeBook && chartInstanceTypeBook.dispose();
  chartInstanceBookType && chartInstanceBookType.dispose();
});

const getUserAll = () => {
  axios({
    url: '/api/admin/adminHerd/getAll',
    method: 'POST',
  })
    .then((res) => {
      userData.value = res.data.data;
      renderChart();
      ElMessage.success('获取用户数据成功');
    })
    .catch((error) => {
      ElMessage.error(error.response?.data?.message || error.message);
    });
};

const getAuthorBookAll = () => {
  axios({
    url: '/apiadmin/adminHerd/getBookAuthorSum',
    method: 'POST',
  })
    .then((res) => {
      AuthorBookData.value = res.data.data;
      renderAuthorBookChart();
      ElMessage.success('获取作者书籍数据成功');
    })
    .catch((error) => {
      ElMessage.error(error.response?.data?.message || error.message);
    });
};

const getTypeBookAll = () => { 
  axios({
    url: '/api/admin/adminHerd/getBookTypeSum',
    method: 'POST',
  })
    .then((res) => {
      TypeBookData.value = res.data.data;
      renderTypeBookChart();
      ElMessage.success('获取书籍类型数据成功');
    })
    .catch((error) => {
      ElMessage.error(error.response?.data?.message || error.message);
    });
};

const getBookTagAll = () => {
  axios({
    url: '/api/admin/adminHerd/getBookTagSum',
    method: 'POST',
  })
    .then((res) => {
      BookTagData.value = res.data.data;
      renderBookTagChart();
      ElMessage.success('获取书籍标签数据成功');
    })
    .catch((error) => {
      ElMessage.error(error.response?.data?.message || error.message);
    });
};

const renderChart = () => {
  if (chartRefUser.value) {
    chartInstanceUser = echarts.init(chartRefUser.value);
    const chartData = userData.value.map((item) => ({
      name: getUserTypeName(item.identity),
      value: item.sum,
    }));

    const option = {
      title: {
        text: '用户类型占比',
        left: 'center',
        textStyle: {
          color: '#333',
        },
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b} : {c} ({d}%)',
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        data: chartData.map((item) => item.name),
      },
      series: [
        {
          name: '用户类型',
          type: 'pie',
          radius: '55%',
          center: ['50%', '60%'],
          data: chartData,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)',
            },
          },
        },
      ],
    };

    chartInstanceUser.setOption(option);
  }
};

const renderAuthorBookChart = () => {
  if (chartRefAuthor.value) {
    chartInstanceAuthor = echarts.init(chartRefAuthor.value);
    const authors = AuthorBookData.value.map((item) => item.author);
    const sums = AuthorBookData.value.map((item) => item.sum);

    const option = {
      title: {
        text: '作者书籍数量',
        left: 'center',
        textStyle: {
          color: '#333',
        },
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow',
        },
      },
      xAxis: {
        type: 'category',
        data: authors,
      },
      yAxis: {
        type: 'value',
      },
      series: [
        {
          name: '书籍数量',
          type: 'bar',
          data: sums,
        },
      ],
    };

    chartInstanceAuthor.setOption(option);
  }
};

const renderTypeBookChart = () => {
  if (charRefTypeBook.value) {
    chartInstanceTypeBook = echarts.init(charRefTypeBook.value);
    const types = TypeBookData.value.map((item) => item.type);
    const sums = TypeBookData.value.map((item) => item.sum);

    const option = {
      title: {
        text: '每个类型的书籍数量',
        left: 'center',
        textStyle: {
          color: '#333',
        },
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow',
        },
      },
      xAxis: {
        type: 'category',
        data: types,
      },
      yAxis: {
        type: 'value',
      },
      series: [
        {
          name: '书籍数量',
          type: 'line',
          step: 'start',
          data: sums,
        },
      ],
    };

    chartInstanceTypeBook.setOption(option);
  }
};

const renderBookTagChart = () => {
  if (chartRefBookType.value) {
    chartInstanceBookType = echarts.init(chartRefBookType.value);
    const tags = BookTagData.value.map((item) => item.bookName);
    const sums = BookTagData.value.map((item) => item.tagSum);
    const option = {
      title: {
        text: '每一个书籍的标签数量',
        left: 'center',
        textStyle: {
          color: '#333',
        },
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow',
        },
      },
      xAxis: {
        type: 'category',
        data:  BookTagData.value.map((item) => item.bookName),
      },
      yAxis: {
        type: 'value',
      },
      series: [
        {
          name: '标签数量',
          type: 'line',
          step: 'start',
          data: sums,
        },
      ],
    };

    chartInstanceBookType.setOption(option);
  }
};

const getUserTypeName = (identity) => {
  switch (identity) {
    case '管理员':
      return '管理员';
    case '作者':
      return '作者';
    case '用户':
      return '用户';
    default:
      return '未知';
  }
};
</script>

<style scoped>
.adminherd-container {
  margin: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  height: auto; /* 使容器占满整个视口高度 */
}

.el-main {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
}

.info-container {
  margin-top: -120px;
  margin-bottom: 20px;
}

.chart {
  width: 100%; /* 使用百分比使图表适应容器大小 */
  max-width: 600px; /* 设置最大宽度 */
  height: 400px;
  margin-bottom: 20px; /* 添加间距 */
}

.user-data {
  margin: auto;
  float: left;
  margin-left: 20px;
}

.AuthorBook-data {
  margin: auto;
  float: left;
  margin-left: 20px;
}
.TypeBook-data{
  margin: auto;
  float: left;
  margin-left: 20px;
}
.BookType-data{
  margin: auto;
  float: left;
  margin-left: 20px;
}
</style>